<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖动框</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
            cursor: move;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="box">aaaaa</div>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script src="../js/bing.js"></script>
    <script>
        let canMove = false   //定义一个变量，表示是否可以移动
        let x = 0  //鼠标在.box中的X轴位置
        let y = 0  //鼠标在.box中的Y轴位置
        $('.box').mousedown(function (e) {
            //鼠标在.box中点击后后，设置可以移动
            canMove = true
            x = e.pageX-$('.box').offset().left
            y = e.pageY-$('.box').offset().top
        })

        $(window).mousemove(function (e) {
            e.preventDefault()  //阻止默认行为
            //判断是否可以移动.box
            if (canMove) {
                let left = e.pageX-x
                let top = e.pageY-y
                let maxLeft = $(window).innerWidth()-$('.box').innerWidth()
                let maxTop = $(window).innerHeight()-$('.box').innerHeight()
                let r = $.filterLeftAndTop(left,top,maxLeft,maxTop)
                $('.box').css({
                    left:r.left+'px',
                    top:r.top+'px'
                })
            }
        }).mouseup(function(){
            //鼠标在当前窗体里面弹起后，设置.box不可以移动
            canMove = false
        }).blur(function(){
            //当前窗体失去焦点后，设置.box不可以移动
            canMove = false
        })
    </script>
</body>

</html>